package com.example.starter.webmvc.util;

import cn.hutool.core.util.ObjUtil;
import lombok.experimental.UtilityClass;

import javax.validation.*;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * @author 王令
 * @since 2022/11/23 9:21
 */
@UtilityClass
public class ValidationUtil {

    private static final ValidatorFactory VALIDATOR_FACTORY = Validation.buildDefaultValidatorFactory();

    public void batchValidate(Collection<?> batch, Class<?>... groups) {
        if (ObjUtil.isEmpty(batch)) {
            return;
        }
        Validator validator = VALIDATOR_FACTORY.getValidator();
        Set<ConstraintViolation<Object>> errResult = new HashSet<>();
        for (Object v : batch) {
            errResult.addAll(validator.validate(v, groups));
        }
        if (ObjUtil.isNotEmpty(errResult)) {
            throw new ConstraintViolationException(errResult);
        }
    }

}
